package hh.util.uuid;

import lombok.Data;

import java.io.Serializable;
import java.util.concurrent.atomic.AtomicInteger;

@Data
public abstract class DistributeIdGenerator<T extends Serializable> implements IdGenerator<T>{



    protected Serializable lastId;
    protected volatile long lastTimestamp = System.currentTimeMillis();
    protected AtomicInteger incr = new AtomicInteger(0);



    @Override
    public T getId() {
        checkTimeStamp(System.currentTimeMillis(), lastTimestamp);
        T serializable = distributeId();
        this.lastId = serializable;
        this.lastTimestamp = System.currentTimeMillis();
        return serializable;
    }

    protected abstract T distributeId();

    protected void checkTimeStamp(long currentTimeMillis, long lastTimestamp) {
        if (currentTimeMillis < lastTimestamp) {
            throw new IllegalStateException("当前时间：{} 必须大于上次生成id时间");
        }
    }


}
